package com.evan.review.architecture.mvc;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.evan.review.R;
import com.evan.review.architecture.mvc.controller.TodoAdapter;
import com.evan.review.architecture.mvc.model.TodoItem;
import com.evan.review.architecture.mvc.model.TodoItemDatabase;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * MVC架构示例Activity
 * 
 * 在MVC架构中:
 * - Model: TodoItem和TodoItemDatabase类，负责数据存储和业务逻辑
 * - View: 本Activity的布局文件和RecyclerView中的item布局
 * - Controller: 本Activity类和TodoAdapter类，负责处理用户输入并更新Model和View
 * 
 * MVC的特点:
 * 1. 简单直观，适合小型应用
 * 2. Activity/Fragment既是View又是Controller，职责不够清晰
 * 3. Controller和View紧密耦合，难以单元测试
 * 4. 随着应用复杂度增加，代码会变得难以维护
 */
public class MVCExampleActivity extends AppCompatActivity implements TodoAdapter.TodoItemClickListener {
    
    private RecyclerView rvTodoList;
    private TextView tvEmptyView;
    private TextView tvTodoCount;
    private FloatingActionButton fabAddTodo;
    
    private TodoAdapter todoAdapter;
    private TodoItemDatabase database;
    private List<TodoItem> todoItems;
    
    // 用于添加/编辑待办事项的对话框
    private AlertDialog todoDialog;
    private EditText etTitle;
    private EditText etDescription;
    private TextView tvDueDate;
    private RadioGroup rgPriority;
    private Button btnSetDate;
    private long selectedDueDate;
    private TodoItem currentEditItem;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mvc_example);
        
        // 设置标题
        setTitle("MVC架构 - 待办事项应用");
        
        // 初始化数据
        database = TodoItemDatabase.getInstance();
        todoItems = new ArrayList<>();
        
        // 初始化视图
        initViews();
        
        // 加载数据
        loadTodoItems();
    }
    
    private void initViews() {
        rvTodoList = findViewById(R.id.rv_todo_list);
        tvEmptyView = findViewById(R.id.tv_empty_view);
        tvTodoCount = findViewById(R.id.tv_todo_count);
        fabAddTodo = findViewById(R.id.fab_add_todo);
        
        // 设置RecyclerView
        rvTodoList.setLayoutManager(new LinearLayoutManager(this));
        todoAdapter = new TodoAdapter(this, todoItems, this);
        rvTodoList.setAdapter(todoAdapter);
        
        // 设置添加按钮点击事件
        fabAddTodo.setOnClickListener(v -> showAddTodoDialog(null));
    }
    
    /**
     * 从数据库加载待办事项
     */
    private void loadTodoItems() {
        todoItems.clear();
        todoItems.addAll(database.getAllTodoItems());
        todoAdapter.notifyDataSetChanged();
        
        // 更新UI状态
        updateUIState();
    }
    
    /**
     * 更新UI状态
     */
    private void updateUIState() {
        if (todoItems.isEmpty()) {
            tvEmptyView.setVisibility(View.VISIBLE);
            rvTodoList.setVisibility(View.GONE);
        } else {
            tvEmptyView.setVisibility(View.GONE);
            rvTodoList.setVisibility(View.VISIBLE);
        }
        
        // 更新待办事项计数
        int incompleteCount = database.getIncompleteItemCount();
        tvTodoCount.setText(String.format("待完成: %d / 总计: %d", incompleteCount, todoItems.size()));
    }
    
    /**
     * 显示添加/编辑待办事项对话框
     */
    private void showAddTodoDialog(TodoItem item) {
        currentEditItem = item;
        boolean isEdit = (item != null);
        
        // 创建对话框视图
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_todo, null);
        
        // 初始化对话框视图中的控件
        etTitle = dialogView.findViewById(R.id.et_todo_title);
        etDescription = dialogView.findViewById(R.id.et_todo_description);
        tvDueDate = dialogView.findViewById(R.id.tv_due_date);
        btnSetDate = dialogView.findViewById(R.id.btn_set_date);
        rgPriority = dialogView.findViewById(R.id.rg_priority);
        
        // 如果是编辑模式，填充现有数据
        if (isEdit) {
            etTitle.setText(item.getTitle());
            etDescription.setText(item.getDescription());
            selectedDueDate = item.getDueDate();
            updateDateDisplay();
            
            // 设置优先级
            switch (item.getPriority()) {
                case 1:
                    rgPriority.check(R.id.rb_priority_low);
                    break;
                case 2:
                    rgPriority.check(R.id.rb_priority_medium);
                    break;
                case 3:
                    rgPriority.check(R.id.rb_priority_high);
                    break;
            }
        } else {
            // 设置默认日期为明天
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            selectedDueDate = calendar.getTimeInMillis();
            updateDateDisplay();
            
            // 默认中优先级
            rgPriority.check(R.id.rb_priority_medium);
        }
        
        // 设置日期选择按钮点击事件
        btnSetDate.setOnClickListener(v -> showDatePicker());
        
        // 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(isEdit ? "编辑待办事项" : "添加待办事项")
                .setView(dialogView)
                .setPositiveButton(isEdit ? "更新" : "添加", (dialog, which) -> {
                    // 保存待办事项
                    saveTodoItem();
                })
                .setNegativeButton("取消", null);
        
        todoDialog = builder.create();
        todoDialog.show();
    }
    
    /**
     * 显示日期选择器
     */
    private void showDatePicker() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(selectedDueDate);
        
        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                (view, year, month, dayOfMonth) -> {
                    Calendar selected = Calendar.getInstance();
                    selected.set(year, month, dayOfMonth);
                    selectedDueDate = selected.getTimeInMillis();
                    updateDateDisplay();
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
        );
        
        datePickerDialog.show();
    }
    
    /**
     * 更新日期显示
     */
    private void updateDateDisplay() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        tvDueDate.setText(dateFormat.format(new Date(selectedDueDate)));
    }
    
    /**
     * 保存待办事项
     */
    private void saveTodoItem() {
        String title = etTitle.getText().toString().trim();
        String description = etDescription.getText().toString().trim();
        
        if (title.isEmpty()) {
            Toast.makeText(this, "标题不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 获取优先级
        int priority;
        int checkedId = rgPriority.getCheckedRadioButtonId();
        if (checkedId == R.id.rb_priority_low) {
            priority = 1;
        } else if (checkedId == R.id.rb_priority_high) {
            priority = 3;
        } else {
            priority = 2; // 默认中优先级
        }
        
        if (currentEditItem == null) {
            // 添加新待办事项
            TodoItem newItem = new TodoItem(
                    0, // ID会在数据库中自动生成
                    title,
                    description,
                    false,
                    selectedDueDate,
                    priority
            );
            database.addTodoItem(newItem);
            Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
        } else {
            // 更新现有待办事项
            currentEditItem.setTitle(title);
            currentEditItem.setDescription(description);
            currentEditItem.setDueDate(selectedDueDate);
            currentEditItem.setPriority(priority);
            database.updateTodoItem(currentEditItem);
            Toast.makeText(this, "更新成功", Toast.LENGTH_SHORT).show();
        }
        
        // 重新加载数据
        loadTodoItems();
    }
    
    // TodoAdapter.TodoItemClickListener接口实现
    
    @Override
    public void onItemClick(TodoItem todoItem) {
        // 点击待办事项，打开编辑对话框
        showAddTodoDialog(todoItem);
    }
    
    @Override
    public void onItemCheckChanged(TodoItem todoItem, boolean isChecked) {
        // 切换待办事项的完成状态
        todoItem.setCompleted(isChecked);
        database.updateTodoItem(todoItem);
        
        // 更新UI状态
        updateUIState();
    }
    
    @Override
    public void onItemDeleteClick(TodoItem todoItem) {
        // 确认删除
        new AlertDialog.Builder(this)
                .setTitle("删除待办事项")
                .setMessage("确定要删除这个待办事项吗？")
                .setPositiveButton("删除", (dialog, which) -> {
                    database.deleteTodoItem(todoItem.getId());
                    loadTodoItems();
                    Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }
} 